package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 分页查询用户列表
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        //当前页的数据
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            String key = Constants.USER_FREEZE + userInfo.getId();
            if(redisTemplate.hasKey(key)){
                userInfo.setUserStatus("2");
            }
        }
        //参数：3.总记录数  4.当前页的数据列表
        return new PageResult(page, pagesize, iPage.getTotal(), list);
    }


    /**
     * 根据id查询
     */
    public UserInfo findUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //查询redis里面的冻结状态
        String key = Constants.USER_FREEZE + userId;
        //判断redis里面是否存在value
        if(redisTemplate.hasKey(key)){
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }


    /**
     * 查询指定用户发布的所有视频列表
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }


    /**
     * 查询动态
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1.调用API查询数据,获取到PageResult对象
        PageResult result = movementApi.findByUserId(uid, page, pagesize, state);

        //2.通过解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();

        //3.一个Movment对象转化一个VO对象
        //判断是否为空
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }

        //获取所有的userId集合
        List<Long> userId = CollUtil.getFieldValues(items, "userId", Long.class);
        //通过userInfoApi获取用户详细信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);

        List<MovementsVo> vos = new ArrayList<>();

        for (Movement movement : items) {
            //获取当前用户人的用户详情
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }

        //4.构造返回值
        result.setItems(vos);
        return result;
    }


    /**
     * 用户冻结
     * */
    public Map userFreeze(Map params) {
        //1.构造一个key
        String userId = params.get("userId").toString();
        //常量定义
        String key = Constants.USER_FREEZE + userId;

        //2.构造它的失效时间
        //冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString()) ;
        int days =0;
        if(freezingTime == 1){
            days =3;
        }else if(freezingTime == 2){
            days=7;
        }

        //3.在将数据传入到redis中
        //存入redis的都是String类型，需要转化
        String value = JSON.toJSONString(params);
        if(days>0){
            //失效时间：单位分钟
            redisTemplate.opsForValue().set(key,value,days, TimeUnit.MINUTES);
        }else{
            redisTemplate.opsForValue().set(key,value);
        }
        Map retMap = new HashMap();
        retMap.put("message","用户冻结成功!");
        return retMap;
    }


    /**
     * 用户解冻
     * */
    public Map userUnfreeze(Map params) {
        //1.获取redis的key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;

        //2.根据key，删除数据
        redisTemplate.delete(key);
        Map retMap = new HashMap();
        retMap.put("message","用户解冻成功！");
        return retMap;
    }
}


